package com.db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

public class StudentsDAO extends AbstractDAO <Students> {
	
	private Statement stm = null;
	private PreparedStatement prepstm = null;
	private ResultSet rs = null;
	
	
	@Override
	public void add (Students entity) {
		
		try
		{
			
		connection = getConnection();
		prepstm = connection.prepareStatement("INSERT INTO student VALUES (null, ?, ?, ?)");
		prepstm.setString(1, entity.getLogin());
		prepstm.setString(2, entity.getPassword());
		prepstm.setInt(3, entity.getGroup_id());
		prepstm.execute();
		}
		
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		
		
	}

	@Override
	public List <Students> getAll() {
		
		List <Students> studentList = new LinkedList <Students> ();
		
		try {
			connection = getConnection();
			stm = connection.createStatement();
			rs = stm.executeQuery("SELECT * FROM student");
			
			while (rs.next())
			{
				Students student = new Students (rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4));
				studentList.add(student);	
			}
		}
		catch (SQLException e) {	
			e.printStackTrace();
		}
		
		closeConnection();
		return studentList;
	}

	
	@Override
	public void delete(int id) {
	
		try {
			connection = getConnection();
			prepstm = connection.prepareStatement("DELETE * FROM student WHERE id = ?");
			prepstm.setInt(1, id);
			prepstm.execute();
			
		} 
		catch (SQLException e) {
			e.printStackTrace();
		}
		
		
		
	}

	

	@Override
	public Students getById (int id) throws SQLException {
		
		Students st = null;
		
		try
		{
			connection = getConnection();
			prepstm = connection.prepareStatement("SELECT * FROM student WHERE id = ?");
			prepstm.setInt(1, id);
			rs = prepstm.executeQuery();
			
		}
		
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		if (rs.next())
		{
			st = new Students (rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4));
		}
		
		return st;
	}

	
	
}
